import React, { Component } from 'react'
import store from '../../store'
import { changeInputAction, addItemAction, ctrlzAction, ctrlyAction } from '../../store/actionCreators'
import DataListUI from './DataListUI'
import { cloneDeep } from 'lodash';

// 最大回退操作步骤
const maxStep = 10;
const undoQueue = []; // 撤销(ctrl+z)
let redoQueue = []; // 重做/还原(ctrl+y)

class DataList extends Component {
    constructor(props) {
        super(props)
        this.state = store.getState();
        this.changeInputValue = this.changeInputValue.bind(this);
        this.storeChange = this.storeChange.bind(this); // 转变this指向
        this.clickBtn = this.clickBtn.bind(this);
        this.ctrlzBtn = this.ctrlzBtn.bind(this);
        this.ctrlyBtn = this.ctrlyBtn.bind(this);
        store.subscribe(this.storeChange) //订阅Redux的状态
    }
    render() {
        return (
            <DataListUI
                inputValue={this.state.inputValue}
                list={this.state.list}
                changeInputValue={this.changeInputValue}
                clickBtn={this.clickBtn}
                ctrlzBtn={this.ctrlzBtn}
                ctrlyBtn={this.ctrlyBtn}
            />
        )
    }
    storeChange() {
        this.setState(store.getState());
    }
    // 表单输入
    changeInputValue(e) {
        const action = changeInputAction(e.target.value);
        console.log("action");
        console.log(action);
        store.dispatch(action);
    }
    // 添加
    clickBtn() {
        const action = addItemAction();
        if (!this.state.inputValue) return;
        store.dispatch(action);
        const snap = cloneDeep(store.getState());
        if (undoQueue.length >= maxStep) {
            undoQueue.shift();
        }
        undoQueue.push(snap);
        console.log("数据");
        console.log(undoQueue);
        // 注意！！每次执行命令时清空重做栈
        redoQueue = [];
    }
    // 撤销
    ctrlzBtn() {
        // const action = ctrlzAction();
        // store.dispatch(action);
        const snap = cloneDeep(store.getState());
        const c = cloneDeep(undoQueue[undoQueue.length - 1]);
        // setComponents(c);
        redoQueue.push(snap);
        undoQueue.pop();
        console.log('undo', undoQueue, redoQueue);
    }
    // 重做/还原
    ctrlyBtn() {
        // const action = ctrlyAction();
        // store.dispatch(action);
        const snap = cloneDeep(store.getState());
        const c = cloneDeep(redoQueue[redoQueue.length - 1]);
        // setComponents(c);
        undoQueue.push(snap);
        redoQueue.pop();
        console.log('redo', undoQueue, redoQueue);
    }
}

export default DataList;